import time

import ddddocr
import requests
from selenium.webdriver.common.by import By

from utils.page import Page


class PageLogin(Page):
    '''
    登录页面类:提供登录页面的操作
    '''
    def __init__(self):
        super(PageLogin, self).__init__()
        self.url = 'http://120.53.243.26:8009/#/login'
        self.loc_username = (By.CSS_SELECTOR, '#app > div > section > main > div > div.left_cls > form > div:nth-child(2) > div > div > input')
        self.loc_password = (By.CSS_SELECTOR, '#app > div > section > main > div > div.left_cls > form > div.el-form-item.el-tooltip.is-required.el-form-item--medium > div > div > input')
        self.loc_verifyvode = (By.CSS_SELECTOR, '#app > div > section > main > div > div.left_cls > form > div:nth-child(4) > div > div > div > input')
        self.loc_verifycode_png = (By.CSS_SELECTOR, '#app > div > section > main > div > div.left_cls > form > div:nth-child(4) > img')
        self.loc_login_button = (By.CSS_SELECTOR, '#aaa')

    def open(self):
        """
        打开登录页面
        """
        self.driver.get(self.url)

    def input_username(self,  username):
        '''
        输入账号
        :return:
        '''
        self.input(username, *(self.loc_username))

    def input_password(self, password):
        '''
        输入密码
        :return:
        '''
        self.input(password, *(self.loc_password))

    def get_verifycode_png(self):
        '''
        获取验证码图片元素(img)
        :return:图片元素,非None:找到;None:没找到
        '''
        return self.find(*(self.loc_verifycode_png))



    def input_verifycode(self):
        '''
        输入验证码
        :return:
        '''
        vcode = self.get_verifycode_png()
        if vcode is not None:
            # 将验证码截图保存
            vcode.screenshot('vcode.png')
            ocr = ddddocr.DdddOcr()
            with open('vcode.png', mode='rb') as f:
                # 对验证码图片进行识别
                vcode = ocr.classification(f.read())
                time.sleep(3)
                # 输入验证码
                self.input(vcode, *(self.loc_verifyvode))

    def click_login_button(self):
        '''
        点击登录按钮
        :return:
        '''
        self.click(*(self.loc_login_button))

    def do_login(self, username, password):
        '''
        完成登录操作
        :return:
        '''
        self.open()
        self.input_username(username)
        self.input_password(password)
        time.sleep(5)
        self.input_verifycode()
        self.click_login_button()

if __name__ == '__main__':
    pl = PageLogin()
    pl.do_login('admin','123456')
    time.sleep(20)